package model

import (
	"gin/config"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Name     string `gorm:"type:varchar(191);not null" json:"name" validate:"required,string,min:3,max:100" label:"用户名"`
	Email    string `gorm:"type:varchar(191);not null" json:"email" validate:"string,min:5,max:190" label:"邮箱"`
	Password string `gorm:"type:varchar(191);not null" json:"password" validate:"required,string,min:5,max:100" label:"密码"`
	Role     int    `gorm:"type:int;default:0" json:"role" validate:"required,gte:0" label:"权限"`
}

// Login 登录方法
func Login(username, password string) (User, int) {
	var user User
	DB.Where("name = ?", username).First(&user)
	if user.ID == 0 {
		return user, config.ErrorUserNotExist
	}
	passwordErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	if passwordErr != nil {
		return user, config.ErrorPasswordWrong
	}
	if user.Role == 0 {
		return user, config.AuthError
	}
	return user, config.SUCCESS
}

// GetInfoByName 根据用户名获取用户信息
func GetInfoByName(name string) (User, int) {
	var user User
	err := DB.Where("name = ?", name).First(&user).Error
	if err != nil {
		return user, config.ERROR
	}
	return user, config.SUCCESS
}
